using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace CodePlex.EnterpriseFramework
{
    public class Utilities
    {
        /// <summary>
        /// This method deserialize the incomming data to the T datatype, this method used to deserialize the test cases data to the required entity
        /// </summary>
        /// <typeparam name="T">Generic to provide returned type</typeparam>
        /// <param name="xmlData">XmlNode that represents data</param>
        /// <returns>T type object that will be filled with xmlData"/></returns>
        public static T Deserialize<T>(XmlNode xmlData)
        {
            // Construct an instance of the XmlSerializer with the type
            // of object that is being deserialized.
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            // To read the xml data stream, create a XmlReader obj.
            XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlData);
            // Call the Deserialize method and cast to the generic <T> type.
            T deserializedObj = (T)xmlSerializer.Deserialize(xmlNodeReader);
            // Return deserialized object
            return deserializedObj;
        }


        /// <summary>
        /// Get file contents into file stream
        /// </summary>
        /// <param name="filePath">File Path</param>
        /// <returns>File Data</returns>
        public static Byte[] GetFileStream(string filePath)
        {
            FileStream fStream = File.OpenRead(filePath);
            byte[] contents = new byte[fStream.Length];
            fStream.Read(contents, 0, (int)fStream.Length);
            fStream.Close();
            return contents;
        }


        public static string NormalizeSharepointAttName(string attName)
        {
            return attName.Replace("ows_", "");
        }

        public static string NormalizeSharepointAttValue(string attValue, int index)
        {
            if (attValue.IndexOf(";#") > 0 && index != -1)
            {                
                string[] values = attValue.Split('#');
                if (values.Length - 1 >= index)
                {
                    string value = values[index];
                    return value.Substring(0, value.Length-1);
                }
                else
                {
                    return attValue;
                }
            }
            else
            {
                return attValue;
            }
        }
    }
}
